package com.hsy.crm.web.web;

import com.hsy.crm.web.domain.cm.Response;
import com.hsy.crm.web.domain.cm.Unified;
import com.hsy.crm.web.domain.vo.platform.CreateVo;
import com.hsy.crm.web.domain.vo.platform.RegCodeVo;
import com.hsy.crm.web.service.impl.PlatCustomerService;
import com.hsy.crm.web.utils.ExpiryMap;
import com.hsy.crm.web.utils.RandomUtils;
import com.hsy.crm.web.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/platform")
public class PlatformAction extends BaseAction{

    Logger logger = LoggerFactory.getLogger(PlatformAction.class);

    @Autowired
    PlatCustomerService platCustomerService;

    /**
     * 发送验证码
     */
    @RequestMapping("/code")
    public String code(RegCodeVo regCodeVo) {
        Unified<Integer> unified = new Unified<>();
        String key = regCodeVo.getCustomerId()+regCodeVo.getPhone();
        Object codeObj = ExpiryMap.get(key);
        String code;
        if( codeObj != null ){
            code = codeObj.toString();
        }else{
            code = RandomUtils.randomInt(4);
        }

        ExpiryMap.put(key,code,600000);//5分钟  300秒
        logger.info("验证码：{}",code);
        //SmsUtils.send(regCodeVo.getPhone(),code);
        return Response.body(unified);
    }

    /**
     * 创建套账
     */
    @RequestMapping("/create")
    public String create(CreateVo createVo) {
        Unified unified = platCustomerService.create(createVo);
        return StringUtils.getScriptValue("parent.created("+Response.body(unified)+")");
    }

    /**
     * 注册
     */
    @RequestMapping("/reg")
    public String reg(RegCodeVo regCodeVo) {

        if( regCodeVo == null || StringUtils.isEmpty(regCodeVo.getPhone()) || StringUtils.isEmpty(regCodeVo.getCode()) ){
            return StringUtils.getScriptValue("parent.reged({result:-100})");
        }

        Object code = ExpiryMap.get(regCodeVo.getCustomerId()+regCodeVo.getPhone());

        if( code == null || !code.toString().equals(regCodeVo.getCode())){
            return StringUtils.getScriptValue("parent.reged({result:-100})");
        }else {
            Unified unified = platCustomerService.regedit(regCodeVo);
            return StringUtils.getScriptValue("parent.reged("+Response.body(unified)+")");
        }

    }

}
